#include "delay.h"
#include "w55mh32.h"
#include <stdint.h>

#define MAX_LOAD 0xFFFFFF

static uint8_t g_us_number = 0;
static uint16_t g_ms_number = 0;
static uint32_t g_max_us = 0;

void delay_init() {
  RCC_ClocksTypeDef clocks;
  RCC_GetClocksFreq(&clocks);
  SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8);
  UsNumber = clocks.SYSCLK_Frequency / 8 / 1000000;
  g_ms_number = (u16)g_us_number * 1000;
  g_max_us = MAX_LOAD / g_us_number;
}

void delay_us(u32 nus) {
  u32 temp = 0;
  SysTick->LOAD = nus * g_us_number;
  SysTick->VAL = 0x00;
  SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk;
  do {
    temp = SysTick->CTRL;
  } while ((temp & 0x01) && !(temp & (1 << 16)));
  SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
  SysTick->VAL = 0X00;
}

void delay_ms(u16 nms) {
  u32 temp = 0;
  do {
    SysTick->LOAD = (nms * 1000 > g_max_us) ? (g_max_us * g_us_number)
                                            : (((u32)nms * g_ms_number));
    nms -= (SysTick->LOAD / g_ms_number);
    SysTick->VAL = 0x00;
    SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk;
    do {
      temp = SysTick->CTRL;
    } while ((temp & 0x01) && !(temp & (1 << 16)));
    SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
    SysTick->VAL = 0X00;

  } while (nms > 0);
}
